# Review routes
from flask import Blueprint, request, jsonify, session
from app.models.review import (
    create_review, get_reviews, get_review_by_id,
    update_review, delete_review, get_review_stats
)
from app.models.order import get_order_detail
from app.models.user import get_user_by_id

review_bp = Blueprint('review', __name__)

@review_bp.route('/reviews', methods=['GET'])
def get_reviews_api():
    """Get review list"""
    order_id = request.args.get('order_id', type=int)
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    try:
        reviews, total = get_reviews(order_id, page, per_page)
        return jsonify({
            'reviews': reviews,
            'total': total,
            'page': page,
            'per_page': per_page
        })
    except Exception as e:
        return jsonify({'error': f'Failed to get reviews: {str(e)}'}), 500

@review_bp.route('/reviews', methods=['POST'])
def create_review_api():
    """Create review"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    data = request.get_json()
    if not data:
        return jsonify({'error': 'Please provide review information'}), 400
    
    order_id = data.get('order_id')
    rating = data.get('rating')
    comment = data.get('comment', '')
    reviewer_name = data.get('reviewer_name', '')
    
    if not order_id or not rating:
        return jsonify({'error': 'Please provide order ID and rating'}), 400
    
    if not isinstance(rating, int) or rating < 1 or rating > 5:
        return jsonify({'error': 'Rating must be an integer between 1-5'}), 400
    
    try:
        # Verify order exists and belongs to current user
        order = get_order_detail(order_id, user_id)
        if not order:
            return jsonify({'error': 'Order does not exist'}), 404
        
        # Check if order is completed
        if order['status'] != 'completed':
            return jsonify({'error': 'Can only review completed orders'}), 400
        
        # Get user information
        user = get_user_by_id(user_id)
        if not user:
            return jsonify({'error': 'User does not exist'}), 404
        
        # Check if already reviewed
        existing_reviews, _ = get_reviews(order_id)
        if any(r['user_id'] == user_id for r in existing_reviews):
            return jsonify({'error': 'This order has already been reviewed'}), 400
        
        review_id = create_review(
            user_id=user_id,
            order_id=order_id,
            rating=rating,
            comment=comment,
            reviewer_name=reviewer_name or user['username']
        )
        
        review = get_review_by_id(review_id)
        return jsonify({
            'message': 'Review created successfully',
            'review': review
        }), 201
        
    except Exception as e:
        return jsonify({'error': f'Failed to create review: {str(e)}'}), 500

@review_bp.route('/reviews/<int:review_id>', methods=['GET'])
def get_review_api(review_id):
    """Get single review"""
    try:
        review = get_review_by_id(review_id)
        if not review:
            return jsonify({'error': 'Review does not exist'}), 404
        
        return jsonify({'review': review})
    except Exception as e:
        return jsonify({'error': f'Failed to get reviews: {str(e)}'}), 500

@review_bp.route('/reviews/<int:review_id>', methods=['PUT'])
def update_review_api(review_id):
    """Update review"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    data = request.get_json()
    if not data:
        return jsonify({'error': 'Please provide update data'}), 400
    
    try:
        # Verify review exists and belongs to current user
        review = get_review_by_id(review_id)
        if not review:
            return jsonify({'error': 'Review does not exist'}), 404
        
        if review['user_id'] != user_id:
            return jsonify({'error': 'No permission to modify this review'}), 403
        
        success = update_review(
            review_id=review_id,
            user_id=user_id,
            rating=data.get('rating'),
            comment=data.get('comment')
        )
        
        if not success:
            return jsonify({'error': 'Update failed'}), 500
        
        updated_review = get_review_by_id(review_id)
        return jsonify({
            'message': 'Review updated successfully',
            'review': updated_review
        })
        
    except Exception as e:
        return jsonify({'error': f'Failed to update review: {str(e)}'}), 500

@review_bp.route('/reviews/<int:review_id>', methods=['DELETE'])
def delete_review_api(review_id):
    """Delete review"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    try:
        # Verify review exists and belongs to current user
        review = get_review_by_id(review_id)
        if not review:
            return jsonify({'error': 'Review does not exist'}), 404
        
        if review['user_id'] != user_id:
            return jsonify({'error': 'No permission to delete this review'}), 403
        
        success = delete_review(review_id, user_id)
        if not success:
            return jsonify({'error': 'Delete failed'}), 500
        
        return jsonify({'message': 'Review deleted successfully'})
        
    except Exception as e:
        return jsonify({'error': f'Failed to delete review: {str(e)}'}), 500

@review_bp.route('/reviews/stats', methods=['GET'])
def get_review_stats_api():
    """Get review statistics"""
    try:
        stats = get_review_stats()
        return jsonify(stats)
    except Exception as e:
        return jsonify({'error': f'Failed to get review statistics: {str(e)}'}), 500
